import { defineStore } from 'pinia'
import { menuApi } from '@/api/menu'

export const useMenuStore = defineStore('menu', {
  state: () => ({
    menuTree: [],
    loading: false,
    error: null,
    flatMenuList: [] // 新增扁平化菜单列表，便于查找
  }),
  actions: {
    async fetchMenuTree() {
      this.loading = true
      this.error = null
      try {
        const data = await menuApi.getMenuTree()
        this.menuTree = data
        this.generateFlatMenuList(data) // 生成扁平化列表
      } catch (err) {
        this.error = err
        console.error('获取菜单失败:', err)
        throw err // 抛出错误以便组件可以捕获
      } finally {
        this.loading = false
      }
    },

    // 生成扁平化菜单列表
    generateFlatMenuList(menuTree) {
      const flatten = (menus) => {
        return menus.reduce((acc, menu) => {
          // 确保 isActive 有默认值
          const menuWithDefaults = {
            isActive: menu.isActive !== false, // 默认为 true
            ...menu
          }
          acc.push(menu)
          if (menu.children && menu.children.length > 0) {
            acc.push(...flatten(menu.children))
          }
          return acc
        }, [])
      }
      this.flatMenuList = flatten(menuTree)
    },

    // 刷新菜单数据
    async refreshMenuTree() {
      await this.fetchMenuTree()
    },

    // 根据ID获取菜单项
    getMenuById(id) {
      return this.flatMenuList.find(menu => menu.id === id)
    }
  }
})